<template>
    <div>
      <h1>购物车列表</h1>
      <ul>
        <li v-for="cart in carts" :key="cart.id">
          {{ cart.user }} - {{ cart.product }} - {{ cart.created_at }}
          <button @click="removeCart(cart.id)">删除</button>
        </li>
      </ul>
      <div>
        <input v-model="newCart.user" placeholder="用户ID" />
        <input v-model="newCart.product" placeholder="商品ID" />
        <button @click="addNewCart">添加到购物车</button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { getCarts, addCart, deleteCart } from '@/api/cart';
  
  const carts = ref([]);
  const newCart = ref({ user: '', product: '' });
  
  const fetchCarts = async () => {
    try {
      const response = await getCarts();
      carts.value = response.data;
    } catch (error) {
      console.error('获取购物车数据失败', error);
    }
  };
  
  const addNewCart = async () => {
    try {
      await addCart(newCart.value);
      await fetchCarts();  // 更新购物车列表
      newCart.value = { user: '', product: '' };
    } catch (error) {
      console.error('添加购物车失败', error);
    }
  };
  
  const removeCart = async (id) => {
    try {
      await deleteCart(id);
      await fetchCarts();  // 更新购物车列表
    } catch (error) {
      console.error('删除购物车失败', error);
    }
  };
  
  onMounted(fetchCarts);
  </script>